//
//  SDJSON.m
//  SKinDiary
//
//  Created by pcyang on 16/7/11.
//  Copyright © 2016年 tencent. All rights reserved.
//


#import "SDJSON.h"

@implementation NSObject (SDJSON)
- (id)mutableParsedJSONObjectWithError:(NSError**)error
{
    NSData *data = nil;
    if ([self isKindOfClass:[NSData class]]) {
        data = (NSData *)self;
    } else if ([self respondsToSelector:@selector(dataUsingEncoding:)]) {
        data = [(id)self dataUsingEncoding:NSUTF8StringEncoding];
    }
    
    if( data )
    {
        if( NSClassFromString(@"NSJSONSerialization") != nil )
        {
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:error];
            return result;
        }
        else
        {
            return nil;//[data mutableObjectFromJSONDataWithParseOptions:JKParseOptionStrict error:error];
        }
    }
    else
    {
        if(error)*error = [NSError errorWithDomain:SDErrorDomain code:SDErrorCode_JSONParser_UnSupportedObject userInfo:nil];
        return nil;
    }
}

- (id)parsedJSONObjectWithError:(NSError**)error
{
    NSData *data = nil;
    if ([self isKindOfClass:[NSData class]]) {
        data = (NSData *)self;
    } else if ([self respondsToSelector:@selector(dataUsingEncoding:)]) {
        data = [(id)self dataUsingEncoding:NSUTF8StringEncoding];
    }
    
    if( data )
    {
        if( NSClassFromString(@"NSJSONSerialization") != nil )
        {
            id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:error];
            return result;
        }
        else
        {
            return nil;//[data objectFromJSONDataWithParseOptions:JKParseOptionStrict error:error];
        }
    }
    else
    {
        if(error)*error = [NSError errorWithDomain:SDErrorDomain code:SDErrorCode_JSONParser_UnSupportedObject userInfo:nil];
        return nil;
    }
}

- (id)JSONValue
{
    return [self parsedJSONObjectWithError:nil];
}


- (NSData*)serializedDataResultWithError:(NSError**)error
{
    if( [self isKindOfClass:[NSArray class]] || [self isKindOfClass:[NSDictionary class]] )
    {
        if( NSClassFromString(@"NSJSONSerialization") != nil )
        {
            id result = [NSJSONSerialization dataWithJSONObject:self options:0 error:error];
            return result;
        }
        else
        {
            return nil;//[(NSArray*)self JSONDataWithOptions:0 error:error];
        }
    }
    else
    {
        if(error)*error = [NSError errorWithDomain:SDErrorDomain code:SDErrorCode_JSONParser_UnSupportedObject userInfo:nil];
        return nil;
    }
}

- (NSString*)serializedStringResultWithError:(NSError**)error
{
    NSData* data = [self serializedDataResultWithError:error];
    return [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
}

- (NSString*)JSONRepresentation
{
    return [self serializedStringResultWithError:nil];
}
@end
